home *** CD-ROM | disk | FTP | other *** search
- Path: engnews2.Eng.Sun.COM!usenet
- From: nitin@more.eng.sun.com (Nitin More [CONTRACTOR])
- Newsgroups: comp.lang.c++
- Subject: Re: Creating a pointer to a function "void (*ptrFunction)()" inside a class
- Date: 05 Jan 1996 20:58:30 GMT
- Organization: SunSoft
- Message-ID: <NITIN.96Jan5125830@more.eng.sun.com>
- References: <30ECA10F.3D99@ifu.net>
- NNTP-Posting-Host: more.eng.sun.com
- In-reply-to: Jason Gresh's message of Thu, 04 Jan 1996 22:54:55 -0500
-
- In article <30ECA10F.3D99@ifu.net> Jason Gresh <gresh@ifu.net> writes:
-
- > From: Jason Gresh <gresh@ifu.net>
- > Newsgroups: comp.lang.c++
- > Date: Thu, 04 Jan 1996 22:54:55 -0500
- > Organization: Internet For 'U'
- >
- > Hi,
- >
- > I am trying to create a base class that has a function that the
- > derived class needs to create. In order to do this, I want to create a
- > pointer to a function in the base class that the derived class can then
- > define. This is not a case where an override will work because the
- > number and names of the derived functions is not known. Hopefully this
- > code sample will make this clearer:
- >
- > class BaseClass
- > {
- > int (*ptrFunction)();
- > }
- >
- > class DerivedClass : BaseClass
- > {
- > DerivedClass::DerivedClass();
- > int myFunction(int, int);
- > }
- >
- > DerivedClass::DerivedClass()
- > {
- > ptrFunction = myFunction;
- > }
- >
- > DerivedClass::myFunction(int, int)
- > {
- > // code ....
- > }
- >
- > If I don't make myFunction part of the derived class (global),
- > everything works fine. As soon as I include it in the class, I cannot
- > assign a pointer to it. I am aware that pointers to functions inside
- > the class include the class name in some way ( this is not an issue for
- > global functions). What is the casting (or other) mechanism to make
- > this work?
- >
- > Thanks,
- >
- > Mike Gresh
- >
-
- I feel you are trying to recreate what C++ already provides you,
- which is virtual methods (or even pure virtual methods). You can define a
- function in your BaseClass as virtual and provide default code for it or
- define it as pure virtual and enforce that *all* derived classes provide code
- for it. If you are using virtual functions, the signature of the method in
- the base class as well as in all derived classes must be same.
-
- If you are unfamiliar about the virtual methods, please read your C++ book.
- Let me know if you need more help with this or if I misunderstood your
- question.
-
- -Nitin
- --
- ----------------------------------------------------------------------
- Nitin More
- SunSoft, Bldg 16 Off: (415) 786 7109
- Menlo Park, CA Fax: (415) 786 7957 e-mail: nitin@more.eng.sun.com
- ----------------------------------------------------------------------
-